/**
 *
 */
package com.wolfking.jeesite.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wolfking.jeesite.entity.Menu;
import com.wolfking.jeesite.entity.RoleMenuRelation;
import com.wolfking.jeesite.mapper.MenuMapper;
import com.wolfking.jeesite.mapper.RoleMenuRelationMapper;
import com.wolfking.jeesite.mybatis.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 菜单的service
 * <p>
 *
 * @author wolfking@赵伟伟
 * @mail zww199009@163.com
 * @创作日期 2017年4月27日下午1:59:38
 * @版权 归wolfking所有
 */
@Service
public class MenuService extends BaseService<Menu> {

    @Autowired
    private RoleMenuRelationMapper roleMenuRelationMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public boolean save(Menu menu) {
        final boolean add = super.save(menu);
        //关联最高管理员的角色
        RoleMenuRelation roleMenuRelation = new RoleMenuRelation();
        roleMenuRelation.setMenuId(menu.getId());
        roleMenuRelation.setRoleId(1);
        roleMenuRelationMapper.insert(roleMenuRelation);
        return add;
    }

    @Transactional
    public void updateMenuSort(Menu menu) {
        final Integer sort = menu.getSort();
        menu = getById(menu.getId());
        menu.setSort(sort);
        mapper.updateById(menu);
    }


    @Override
    @Transactional
    public List<Menu> deleteById(Serializable id) {
        List<Menu> menus = super.deleteById(id);
        if (!menus.isEmpty()) {
            LambdaQueryWrapper<RoleMenuRelation> inWrapper = new QueryWrapper<RoleMenuRelation>().lambda().in(
                    RoleMenuRelation::getMenuId, menus.stream().map(Menu::getId).collect(Collectors.toList()));
            roleMenuRelationMapper.delete(inWrapper);
        }
        return menus;
    }

    /**
     * 获取用户有权限的菜单
     *
     * @return
     */
    @Transactional(readOnly = true)
    public List<Menu> getUserMenus(Integer userId) {
        List<Menu> userAllMenu = userId == 1 ? menuMapper.selectList(new QueryWrapper<>()) : menuMapper.getUserAllMenu(userId);
        return userAllMenu.stream()
                .sorted(Comparator.comparingInt(Menu::getSort)).collect(Collectors.toList());
    }

    @Transactional(readOnly = true)
    public List<Menu> getMainUserMenus(Integer userId) {
        return getUserMenus(userId).stream().filter(m -> m.getParentId() == 1)
                .sorted(Comparator.comparingInt(Menu::getSort))
                .collect(Collectors.toList());
    }
}
